package upload;

import utils.StreamUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author xingzhiwen
 * @date 2021/9/14
 * @ddescription:
 */
public class TCPFileUploadServer {
    public static void main(String[] args) throws Exception {
        //服务端在本机，监听8888
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务端在8888监听");
        //等待连接
        Socket socket = serverSocket.accept();

        //读取数据
        // socket获取输入流
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //将得到的byte数组，写入到指定的路径
        String destFilePath = "src\\2.jpg";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
        bos.write(bytes);
        bos.close();

        //向客户端回复收到图片
//        socket 字符流
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write("收到图片");
        writer.flush();
        writer.newLine();

        writer.close();
        bis.close();
        socket.close();
        serverSocket.close();

    }
}
